class Color {
    constructor(color) {
        if (color instanceof Array) {
            this.color = color
        } else if (typeof color === 'string') {
            this.color = parseToArray(color)
        } else {
            this.color = [0, 0, 0, 0]
        }
    }

    static parse(cssColorString) {
        let arr = parseToArray(cssColorString)
        return new this(arr)
    }

    static createGradient(startColor, endColor, step) {
        return createGradient(startColor, endColor, step)
    }

    toHex() {
        return toHex(this.color)
    }

    toRgba() {
        return 'rgba(' + this.color.join(',') + ')'
    }

    modifyAlpha(alpha) {
        this.color[3] = alpha
    }

    toString() {
        return this.toRgba()
    }
}


/**
 * 解析css颜色
 * @param {String} cssColorString css颜色字符
 * #rrggbb
 * #rgb
 * rgb(0, 0, 0)
 * rgba(0, 0, 0, 0)
 */
function parseToArray(cssColorString) {
    let color = [0, 0, 0, 1];
    let str = cssColorString;

    if (!cssColorString) {
        return color;
    }

    if (str.indexOf('#') > -1) {
        let hexColor = str.slice(1);
        if (hexColor.length !== 3 && hexColor.length !== 6) {
            console.error('错误的颜色格式', str);
            return color;
        }

        if (hexColor.length === 3) {
            hexColor = hexColor[0].repeat(2) + hexColor[1].repeat(2) + hexColor[2].repeat(2);
        }

        let value = parseInt(hexColor, 16);

        let r = value >> 16 & 0xFF;
        let g = value >> 8 & 0xFF;
        let b = value & 0xFF;

        color[0] = r;
        color[1] = g;
        color[2] = b;
    }
    else if (str.indexOf('rgb') > -1) {
        str.replace(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/g, function (m, r, g, b, a = 1) {
            color[0] = r * 1;
            color[1] = g * 1;
            color[2] = b * 1;
            color[3] = a * 1;
        });
    }

    return color;

}

/**
 * 将颜色数组转化为十六进制表示
 * @param {Array} color 颜色数组[r, g, b, a]
 */
function toHex(color) {
    let [r, g, b, a] = color;
    let value = r << 16 | g << 8 | b;
    return '#' + ('000000' + value.toString(16)).slice(-6);
}

/**
 * 创建渐变色数组
 * @param {String} startColor 开始颜色
 * @param {String} endColor 结束颜色
 * @param {Number} step 生成中间颜色的数量
 */
function createGradient(startColor, endColor, step) {
    // 0-255 个
    // let value = r << 16 | g << 8 | b;
    let sc = parseToArray(startColor)
    let ec = parseToArray(endColor)

    let rStep = (ec[0] - sc[0]) / step
    let gStep = (ec[1] - sc[1]) / step
    let bStep = (ec[2] - sc[2]) / step
    // let aStep = (sc[3] - ec[3]) / step

    let result = [startColor]

    let a = 1

    for (let i = 1; i < step; i++) {
        let r = parseInt(rStep * i + sc[0])
        let g = parseInt(gStep * i + sc[1])
        let b = parseInt(bStep * i + sc[2])

        result.push(toHex([r, g, b, a]))
    }

    result.push(endColor)

    return result
}


export default Color